<template>
	<view class="container">
		<u-navbar bgColor="#0e3a5e" :title="data.title" :autoBack="true" :safeAreaInsetTop="true" :placeholder="true" leftIconColor="#fff"
			:titleStyle="data.titleStyle">
			<template #right>
				<view class="u-nav-slot" @click="shakedown" v-if="data.listQuery.typeName === 'handover'">
					<text class="shakedownText">下线调试</text>
				</view>
			</template>
		</u-navbar>
		<mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback" :up="upOption">

			<view class="pdBox" v-if="data.list.length">
				<view class="shake_item" v-for="(item,index) in data.list" :key="item.id">
					<view class="shake_top" v-if="item.resultType === 'YN'">
						<text style="width: 80px; color: #fff;"></text>
						<view style="flex: 1;display: flex; justify-content: flex-end;">
							<text style="color:#fff; margin-right:6px;">{{item.ynType?item.ynType.split('-')[1]:''}}</text> <u-switch
								v-model="item.adjustResult"
								:activeColor="item.adjustResult !== null? '#00a846' :'#2979ff'" activeValue="Y"
								inactiveValue="N" :inactiveColor="item.adjustResult !== null? '#dc362e' : '#ffffff'"
								@change="change($event,item)"></u-switch> <text
								style="color:#fff; margin-left:6px;">{{item.ynType?item.ynType.split('-')[0]:''}}</text>
						</view>
					</view>
					<view class="shake_top" v-if="item.resultType === 'VAL'">
						<text style="width: 80px; color: #fff;"></text>
						<view style="width: 200px;display: flex; justify-content: flex-end;">
							<u--input border="bottom" v-model="item.adjustResult" placeholder="输入调试结果"
								@blur="saveResult(item)" placeholderStyle="color:#000"></u--input>
							<text style="margin-left: 6px;width: 70px;line-height: 34px;"
								@click="openPicker(item,index)">{{item.unit?filterUnit(item.unit): '选择单位'}}</text>
						</view>
					</view>
					<view class="shake_bottom">
						<view class="shake_bottom_item">
							<text class="shake_bottom_l">部位</text>
							<text class="shake_bottom_r">{{item.adjustPart}}</text>
						</view>
						<view class="shake_bottom_item">
							<text class="shake_bottom_l">检查项目</text>
							<text class="shake_bottom_r">{{item.adjustItem}}</text>
						</view>
						<view class="shake_bottom_item" v-if="item.isExpand">
							<text class="shake_bottom_l">工艺/检验标准</text>
							<text class="shake_bottom_r">{{item.standard}}</text>
						</view>
						<view class="shake_bottom_item" v-if="item.isExpand">
							<text class="shake_bottom_l">检验方法/器具</text>
							<text class="shake_bottom_r">{{item.adjustMethod}}</text>
						</view>
						<view class="shake_bottom_item" v-if="item.isExpand">
							<text class="shake_bottom_l">图片</text>
							<view class="shake_bottom_r">
								<u-upload :fileList="item.keyfiles" @afterRead="afterRead" :name='`${item.id}`'
									@delete="deletePic" multiple :previewFullImage="true"></u-upload>
							</view>
						</view>
						<view class="shake_bottom_item" v-if="item.isExpand">
							<text class="shake_bottom_l">备注</text>
							<view class="shake_bottom_r">
								<u--textarea v-model="item.memo" placeholder="请输入内容"
									@focus="showBtn(item)"></u--textarea>
							</view>
						</view>
						<view class="" v-if="item.isExpand && item.isBtnShow">
							<u-button type="primary" :throttleTime="1000" text="添加备注" style="width: 40%;" @click="saveMemo(item)"></u-button>
						</view>
					</view>
					<view class="lookMore"  @click="item.isExpand = !item.isExpand">
						<u--image src="../../static/Vector.png" width="46rpx" height="28rpx" ></u--image>
					</view>
				</view>
			</view>
		</mescroll-body>

		<u-picker :show="data.pickerShow" keyName="measureName" :columns="data.pickerColumns" @cancel="data.pickerShow = false"
			@confirm="chooseUnit"></u-picker>
	</view>
</template>

<script lang="ts" setup>
	import {
		getAdjustItemList,
		adjusttypeitemSave,
		itemFiledelete,
		adjusttypeBatchPass,
		getAjusttypeList,
		updateStatus,
		getUnitList
	} from '@/api/planList/planList.js'
	import {
		reactive,
	} from "vue";
	import {
		onShow,
		onLoad,
		onReachBottom,
		onPageScroll
	} from "@dcloudio/uni-app";
		import useMescroll from "@/uni_modules/mescroll-uni/hooks/useMescroll.js";
	import dayjs from 'dayjs';
	import base from "@/common/baseUrl.js";
	const base_url = base.baseUrl;

	const upOption = {
		noMoreSize: 10, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
		textNoMore: '-- 没有更多啦 --', // 没有更多数据的提示文本
		empty: {
			tip: '~ 暂无数据 ~' // 提示
		}
	}

	const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom)

	const data = reactive({
		list: [],
		title:'',
		listQuery: {
			typeName: null,
			planEqmId: null,
		},
		titleStyle: {
			color: '#fff',
			fontSize: '34rpx',
			fontWeight: '600'
		},
		noMore: false,
		modalShow: false,
		modalType: 'add',
		form: {
			recordBy: ''
		},
		pickerShow: false,
		pickerColumns: [],
		listIndex: null,
		typeId: null,
		countAll: null,
		countUnHandle: null,
	})
	onLoad((option) => {
		if (option.planEqmId) {
			data.listQuery.planEqmId = option.planEqmId
		}
		if (option.typeName) {
			data.listQuery.typeName = option.typeName
		}
		getUnitList().then(res => {
			data.pickerColumns = [res.rows]
		})
		getCount()
	})
	onShow(() => {
	
	})
	const upCallback = async (mescroll) => {
		try {
			const params = {
				current: mescroll.num,
				size: mescroll.size,
				planEqmId: data.listQuery.planEqmId,
				typeName: data.listQuery.typeName,
			}
			const res = await getAdjustItemList(params)
			const curPageData = res.data.records || [] // 当前页数据
			if (mescroll.num == 1) data.list = []; // 第一页需手动制空列表
			data.list = data.list.concat(curPageData)
			data.list.map(item => {
				let keyfiles = []
				if (item.files && item.files.length) {
					item.files.map(i => {
						const keyfilesObj = {
							fileId: i.id,
							itemId: item.id,
							url: i.uri
						}
						keyfiles.push(keyfilesObj)
					})

				}
				item.keyfiles = keyfiles
				item.isExpand = false
				item.isBtnShow = false
			})
			mescroll.endByPage(curPageData.length, res.data.total);
		} catch (e) {

			//TODO handle the exception
		}
	}
	const getCount = () => {
		if (data.listQuery.typeName === 'handover') {
			getAjusttypeList({ planEqmId: data.listQuery.planEqmId, adjustType: 'handover', current: 1, size: 10 }).then(res => {
				data.typeId = res.data.records[0].typeId
				data.countAll = res.data.records[0].countAll
				data.countUnHandle = res.data.records[0].countUnHandle
				data.title= `转序交接(${res.data.records[0].countAll - res.data.records[0].countUnHandle}/${res.data.records[0].countAll})`
			})
		} else {
			getAjusttypeList({ planEqmId: data.listQuery.planEqmId, adjustType: 'offline_inspection', current: 1, size: 10 }).then(res => {
				if (res.data.records.length) {
					data.typeId = res.data.records[0].typeId
					data.countAll = res.data.records[0].countAll
					data.countUnHandle = res.data.records[0].countUnHandle
					data.title= `转序交接(${res.data.records[0].countAll - res.data.records[0].countUnHandle}/${res.data.records[0].countAll})`
				} else {
					data.title=  `下线点检`
				}

			})
		}
	}

	const change = (e, item) => {
		const obj = { ...item }
		adjusttypeitemSave(obj).then((res) => {
			if (res.status === 200) {
				uni.showToast({
					title: '操作成功',
					icon: 'none'
				})
				getCount()
			}
		});
	}
	const saveResult = (item) => {
		if (item.unit) {
			adjusttypeitemSave(item).then(res => {
				getMescroll().resetUpScroll()
				data.pickerShow = false
			})
		}
	}
	const filterUnit = (val : any) => {
		const index = data.pickerColumns[0].findIndex((item) => item.measureCode === val);
		return index !== -1 ? data.pickerColumns[0][index].measureName : "";
	}
	const afterRead = (e) => {
		const itemId = e.name;
		let files = e.file;
		if (files.length) {
			files.map(async (item) => {
				uni.uploadFile({
					url: base_url + '/proplan/plan/adjusttype/item/fileupload', //接口
					filePath: item.thumb,
					name: 'file',
					header: {
						Authorization: uni.getStorageSync("access_token"),
					},
					file: item,
					formData: {
						itemId
					},
					success: async res => {
						let resData = JSON.parse(res.data);
						if (resData.status == 200 && resData.data.uri) {
							data.list.map((i) => {
								if (i.id == itemId) {
									i.keyfiles.push({
										fileId: resData.data.id,
										itemId: itemId,
										url: resData.data.uri
									})
								}
							})
						}
					}
				})
			})
		}
	}
	const deletePic = (e) => {
		uni.showModal({
			title: '提示',
			content: '确认要删除该条数据吗？',
			success: function (res) {
				if (res.confirm) {
					const index = data.list.findIndex(item => item.id == e.file.itemId)
					itemFiledelete(e.file.itemId, e.file.fileId).then(res => {
						data.list[index].keyfiles.splice(e.index, 1)
					})
				}
			}
		});
	}
	const openPicker = (item, index) => {
		data.listIndex = index
		data.pickerShow = true
	}
	const chooseUnit = (item) => {
		data.list[data.listIndex].unit = item.value[0].measureCode
		if (data.list[data.listIndex].adjustResult) {
			adjusttypeitemSave(data.list[data.listIndex]).then(res => {
				uni.showToast({
					title: '操作成功',
					icon: 'none'
				})
				// getData()
				data.pickerShow = false
			})
		}
	}
	const showBtn = (item) => {
		item.isBtnShow = true
	}
	const saveMemo = (item) => {
		adjusttypeitemSave(item).then((res) => {
			if (res.status === 200) {
				uni.showToast({
					title: '操作成功',
					icon: 'none'
				})
				item.isBtnShow = false
			}
		});
	}
	const formatDate = (val) => {
		return dayjs(val * 1000).format('YYYY-MM-DD');
	}
	const batchPass = async () => {
		data.listQuery.planEqmId = Number(data.listQuery.planEqmId)
		const { planEqmId } = data.listQuery
		const res = await adjusttypeBatchPass({ planEqmId, typeId: data.typeId })
		if (data.listQuery.typeName === 'handover') {
			uni.setNavigationBarTitle({
				title: `转序交接(${data.countAll}/${data.countAll})`
			});
		} else {
			uni.setNavigationBarTitle({
				title: `下线点检(${data.countAll}/${data.countAll})`
			});
		}
		uni.showToast({
			title: '操作成功',
			icon: 'none'
		})
		getMescroll().resetUpScroll()
	}
	const shakedown = () => {
		uni.showModal({
			title: '提示',
			content: '确认执行下线调试操作吗？',
			success:async function (sres) {
				if (sres.confirm) {
					const obj = {
						id: data.listQuery.planEqmId,
						status: 'WGTS',
						statusName: '完工调试'
					}
					updateStatus(obj).then(res => {
						if (res.status === 200) {
							uni.showToast({
								title: '操作成功',
								icon: 'none'
							})
							uni.reLaunch({
								url: '/pages/planList/planList'
							})
						}
					})
				} 
			}
		});
		
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 90vh;
		padding-bottom: 160rpx;
	}

	.shake_item {
	
		background: #fff;
		margin-top: 20rpx;
		border-radius: 20rpx;
		box-shadow: 0 0 10rpx 0 #bbbbbb;
		overflow: hidden;
		margin-bottom: 60rpx;
		.shake_top {
			border-radius: 20rpx 20rpx 0 0;
			background: #0081fe;
			padding: 24rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			
		}
	
		.shake_bottom {
			background-color: #fff;
			padding: 24rpx;
			// border-left:  2px solid #000;
			// border-right:  2px solid #000;
			.shake_bottom_item {
				border-bottom: 1px solid #eeeeee;
				padding: 20rpx 0;
				font-size: 16px;
				display: flex;
				justify-content: space-between;
				align-items: flex-start;
	
				.shake_bottom_l {
					width: 30%;
				}
	
				.shake_bottom_r {
					flex: 1;
					color: #3975c6;
				}
	
			}
		}
		.lookMore{
			padding: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			padding-bottom: 40rpx;
			.more{
				margin-right: 20rpx;
				font-size: 28rpx;
				color: #999999;
			}
		}
	}
	
	.special_shake {
		background-color: #fff;
		margin-top: 12px;
		padding: 12px;

		.special_shake_item_top {
			display: flex;
			justify-content: space-between;
		}

		.special_shake_item {
			border-bottom: 1px solid #f8f9f9;
			padding: 6px 0;
			font-size: 16px;
			display: flex;
			justify-content: space-between;
			align-items: flex-start;

			.special_shake_item_l {
				width: 30%;
			}

			.special_shake_item_r {
				flex: 1;
				color: #3975c6;

			}

			.attr {
				display: flex;
				justify-content: space-between;

				.u-button {
					width: 30px !important;
				}
			}
		}
	}

	.shakedownText{
		color: #fff;
		font-size: 30rpx;
		font-weight: bold;
	}
	.type_item {
		padding: 6px 12px;
		border-bottom: 1px solid #EEEFF0;
		color: #0E3A5E;
	}
</style>